package com.study.data.sort;

/**
 * @program: java-study-of-learner
 * @description: 插入排序
 * @author: future
 * @create: 2020-11-21 19:39
 **/
public class InsertionSort {

    public void sort(int[] arr) {
        //1.遍历
        for (int i = 1; i < arr.length; i++) {
            //2.内层比较
            for (int j = i; j > 0; j--) {
                if (arr[j] < arr[j - 1]) {
                    int temp = arr[j];
                    arr[j] = arr[j - 1];
                    arr[j - 1] = temp;
                }
            }
        }
    }

    /**
     * 优化排序（去除多余每次新增变量）
     */
    public void sortOfOptimize(int[] arr) {
        for (int i = 1; i < arr.length; i++) {
            int temp = arr[i];
            int j;
            for (j = i; j > 0 && arr[j - 1] > temp; j--) {
                arr[j] = arr[j - 1];
            }
            arr[j] = temp;
        }
    }
}
